package com.lk.springboot.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.lk.springboot.dao.GameMapper;
import com.lk.springboot.dao.ScheduleMapper;
import com.lk.springboot.dao.ScoreMapper;
import com.lk.springboot.dao.UserMapper;
import com.lk.springboot.pojo.ScoreRu;
import com.lk.springboot.pojo.USHave;
import com.lk.springboot.service.PidUtilService;
import com.lk.springboot.service.ScoreService;
import com.lk.springboot.utils.RandomUtil;
import com.lk.springboot.utils.SubwayMap;
import com.lk.springboot.utils.UseMapApiUtil;
import com.lk.springboot.vo.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author lk
 * @date 2020/1/12 0012 11:29
 */
@Service
public class ScoreServiceImpl implements ScoreService {

    @Autowired
    ScoreMapper scoreMapper;
    @Autowired
    GameMapper gameMapper;
    @Autowired
    UserMapper userMapper;
    @Autowired
    PidUtilService pidUtilService;
    @Autowired
    ScheduleMapper scheduleMapper;

    static final int MAX_MAGIC_TIMES = 3; // 魔法市场交易次数
    static final int CENTER_LOTTERY_SCORE = 20; // 兑换中心抽奖所需积分
    static final int MAGIC_LOTTERY_SCORE = 20; // 魔法市场抽奖所需积分

    @Override
    public Result getSummary(String u_id, String ru_type) {
        //判断是否第一次打开魔法市场，是则执行下一步
        if ("magic".equals(ru_type) && scoreMapper.getUserMagicStatus(u_id) == 0) {
            int scoreCenterNum = 6;
            int magicMarketNum = 4;
            scoreMapper.markMagicStatus(u_id);//标记已经不是第一次打开魔法市场了
            SubwayMap subwayMap = SubwayMap.randomLetter();
            ArrayList<String> list = UseMapApiUtil.parseRequest(subwayMap.getJ(), subwayMap.getW(), 4);//调用高德地图api，获取指定位置处的周围地铁站
            ArrayList<String> pIdList = new ArrayList<>();
            for (String mapid : list) {//根据列表去数据库里找到对应的p_id
                pIdList.add(scoreMapper.getPidByMapid(mapid));
            }
            RandomUtil randomUtil = new RandomUtil();
            List<String> magicRareList = randomUtil.scoreCenterRandomGetRares(1, magicMarketNum);// 魔法市场的 稀有度列表
            ArrayList<String> spIdList = new ArrayList<>();// sp_id列表
            for (int i = 0; i < magicMarketNum; i++) {
                spIdList.add(scheduleMapper.getSPList(pIdList.get(i), magicRareList.get(i)));
            }
            ArrayList<ScruIdAndType> scRuIdTypeList = scheduleMapper.getScoreRu();// 所有规则的列表《scru_id，ru_type》
            for (int i = 0; i < magicMarketNum; i++) {
                scheduleMapper.updateScoreRuSP(scRuIdTypeList.get(i+scoreCenterNum).getScru_id(), spIdList.get(i));
            }
        }

        List<ScoreSummary> list = scoreMapper.getScoreSummary(ru_type);
        //拼接拼图名称
        for (ScoreSummary summary : list) {
            int sp_id_num = Integer.parseInt(summary.getSp_id().replace("sp", "")) % 4;
            if (sp_id_num == 0)
                sp_id_num = 4;
            summary.setSp_name(scoreMapper.getSName(summary.getSp_id()) + "0" + sp_id_num);// 拼接拼图名称
        }
        ArrayList<JSONObject> arrayList = new ArrayList<>();
        if (ru_type.equals("magic")) {//判断是魔法市场兑换（返回魔法市场概述）
            scoreMapper.signMagic(u_id);//逛魔法市场的任务完成
            boolean isBought;
            for (ScoreSummary summary : list) {//判断魔法市场每一个拼图是否都被用户买过
                if (scoreMapper.getIsBought(u_id, summary.getScru_id()) == 1)//已经买过该拼图了
                    isBought = true;
                else //还没买过
                    isBought = false;
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("sp_id", summary.getSp_id());
                jsonObject.put("url", summary.getUrl());
                jsonObject.put("rare", summary.getRare());
                jsonObject.put("scru_id", summary.getScru_id());
                jsonObject.put("score_num", summary.getScore_num());
                jsonObject.put("sp_name", summary.getSp_name());
                jsonObject.put("isBought", isBought);
                arrayList.add(jsonObject);
            }
        } else if (ru_type.equals("score")) { // 判断是积分中心兑换（返回积分兑换中心概述）
            scoreMapper.signScore(u_id);//逛积分中心的任务完成
            for (ScoreSummary summary : list) {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("sp_id", summary.getSp_id());
                jsonObject.put("url", summary.getUrl());
                jsonObject.put("rare", summary.getRare());
                jsonObject.put("scru_id", summary.getScru_id());
                jsonObject.put("score_num", summary.getScore_num());
                jsonObject.put("sp_name", summary.getSp_name());
                arrayList.add(jsonObject);
            }
        }
        Result result = new Result(ResultCode.SUCCESS);
        result.setData(arrayList);
        return result;

    }

    @Override
    public Result scoreExch(String u_id, String scru_id) {
        ScoreRu scoreRu = scoreMapper.getTheScoreRu(scru_id);
        int nowScore = scoreMapper.getScore(u_id); //目前拥有积分
        if (nowScore < scoreRu.getScore_num()) {
            Result result = new Result(ResultCode.REFULSE_REQUEST);
            result.setData("积分不足,不能兑换");
            return result;
        }
        if (scoreRu.getRu_type().equals("magic")) { // 判断该交易规则是 魔法市场的
            if (scoreMapper.getMarketNum(u_id) >= MAX_MAGIC_TIMES) {// 魔法市场交易次数已达到上线
                Result result = new Result(ResultCode.REFULSE_REQUEST);
                result.setData("魔法市场,今日交易次数已经用完,不能再抽奖或兑换拼图");
                return result;
            }
            if (scoreMapper.getIsBought(u_id, scru_id) == 1) { // 该块拼图今日购买已达上限
                Result result = new Result(ResultCode.REFULSE_REQUEST);
                result.setData("对不起,该拼图今日购买已达上限,您可以换一块,或者明天再来");
                return result;
            }
            scoreMapper.alterMagicTimes(u_id);    // 魔法市场交易，次数加一
            scoreMapper.alterIsBought(u_id, scru_id);// 标记魔法市场，相应的得拼图商品已经被用户买过了***
        }
        scoreMapper.reduceScore(u_id, scoreRu.getScore_num());//减积分
        String sp_id = scoreRu.getSp_id();
        String s_id = scoreMapper.getSidBySp(sp_id);// 查s_id
        String p_id = userMapper.getPidBySP(sp_id);// 查p_id
        List<String> list = userMapper.getPidFromActive(u_id, 0);// 获取未激活的p_id列表**
        if (list.contains(p_id)) {
            userMapper.updateActive(u_id, p_id);//记录激活状态
        }
        USHave usHave = new USHave(u_id, s_id, sp_id);
        gameMapper.addPhoto(usHave);// 增加拥有记录
        nowScore = scoreMapper.getScore(u_id); //剩余积分
        Result result = new Result(ResultCode.SUCCESS);
        result.setData(nowScore);
        return result;
    }

    @Override
    public Result centerLottery(String u_id) {
        if (scoreMapper.getScore(u_id) < CENTER_LOTTERY_SCORE) {//目前拥有积分 小于 抽奖所需要的积分
            Result result = new Result(ResultCode.REFULSE_REQUEST);
            result.setData("积分不足,不能抽奖");
            return result;
        }
        RandomUtil randomUtil = new RandomUtil();
        scoreMapper.reduceScore(u_id, CENTER_LOTTERY_SCORE);//【抽奖所扣取的 积分数量】
        List pidList = pidUtilService.getActiveRandomPid(u_id, 1);      // 只能获取用户已经激活过了的 随机p_id*****
        List rareList = randomUtil.CenterRandomGetRares(1);    // 稀有度控制【A B C D】
        GameSP theSiteSP = gameMapper.getSmallPhoto(pidList.get(0).toString(), rareList.get(0).toString());
        String sp_id = theSiteSP.getSp_id();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("sp_id", sp_id);
        int sp_id_num = Integer.parseInt(sp_id.replace("sp", "")) % 4;
        if (sp_id_num == 0)
            sp_id_num = 4;
        String sp_name = scoreMapper.getSName(sp_id) + "0" + sp_id_num;
        jsonObject.put("sp_name", sp_name);                  //拼图名
        jsonObject.put("rare", rareList.get(0).toString());
        jsonObject.put("url", theSiteSP.getUrl());
        jsonObject.put("score", scoreMapper.getScore(u_id));
        String s_id = gameMapper.getSitesBySp(sp_id);
        USHave usHave = new USHave(u_id, s_id, sp_id);//------------------------------------------------------
        gameMapper.addPhoto(usHave);// 增加拥有记录
        Result result = new Result(ResultCode.SUCCESS);
        result.setData(jsonObject);
        return result;
    }

    @Override
    public Result magicLottery(String u_id) {
        if (scoreMapper.getScore(u_id) < MAGIC_LOTTERY_SCORE) {//目前拥有积分 小于 抽奖所需要的积分
            Result result = new Result(ResultCode.REFULSE_REQUEST);
            result.setData("积分不足,不能抽奖");
            return result;
        }
        if (scoreMapper.getMarketNum(u_id) >= MAX_MAGIC_TIMES) { // 魔法市场交易次数已达到上线
            Result result = new Result(ResultCode.REFULSE_REQUEST);
            result.setData("今日交易次数已经用完,不能再抽奖或兑换拼图");
            return result;
        }
        RandomUtil randomUtil = new RandomUtil();
        scoreMapper.reduceScore(u_id, MAGIC_LOTTERY_SCORE);//【抽奖所扣取的 积分数量】
        JSONObject jsonObject = new JSONObject();
        int props_id = randomUtil.MagicRandomGetProps(10003, 10001);//随机道具id
        gameMapper.addPropsNum(u_id, props_id);//增加道具的拥有数量
        jsonObject.put("props_id", props_id);
        jsonObject.put("props_name", gameMapper.getPropsName(props_id));
        Result result = new Result(ResultCode.SUCCESS);
        result.setData(jsonObject);
        scoreMapper.alterMagicTimes(u_id);    // 魔法市场交易，次数加一
        return result;
    }


}
